import 'dart:io';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get_utils/get_utils.dart';

import '../../pages/common/preview_image/index.dart';
import '../../pages/common/video_player/index.dart';
import 'index.dart';

/// webview  工具类
/// 
/// 主要处理 jspai 注入方面的工作
class WebviewHelper {
 
  final channel = O2FlutterMethodChannelUtils();
  // js api 插件
  final  jsHandler = O2JavascriptHandler();

  /// 加载接口实现类
  /// 
  /// 处理窗口相关事件的
  void setupJsNavigationInterface(JsNavigationInterface inf) {
    jsHandler.jsNavigationInterface = inf;
  }

  ///
  /// 加载js通道
  /// 在 webview onWebViewCreated 的时候加载
  ///
  void setupWebviewJsHandler(InAppWebViewController webviewController) async {
    // 添加 webviewController
    jsHandler.webviewController = webviewController;
    // 添加 js handler
    webviewController.addJavaScriptHandler(handlerName: jsHandler.o2mNotification().key, callback: jsHandler.o2mNotification().callback);
    webviewController.addJavaScriptHandler(handlerName: jsHandler.o2mBiz().key, callback: jsHandler.o2mBiz().callback);
    webviewController.addJavaScriptHandler(handlerName: jsHandler.o2mUtil().key, callback: jsHandler.o2mUtil().callback);
  }

  /// 
  /// webview 加载进度
  /// progressChanged == 100的时候加载
  /// 
  void changeJsHandlerFunName(InAppWebViewController c ) {
    var js = '''
          if (window.flutter_inappwebview && window.flutter_inappwebview.callHandler) {
            window.o2mNotification = {};
            window.o2mNotification.postMessage = function(message){
              window.flutter_inappwebview.callHandler('o2mNotification', message);
            };
            window.o2mBiz = {};
            window.o2mBiz.postMessage = function(message){
              window.flutter_inappwebview.callHandler('o2mBiz', message);
            };
            window.o2mUtil = {};
            window.o2mUtil.postMessage = function(message){
              window.flutter_inappwebview.callHandler('o2mUtil', message);
            };
          }
        ''';
    c.evaluateJavascript(source: js);
    OLogger.d("执行o2m jsapi 转化完成。。。");
  }

  ///
  /// webview 下载文件 支持
  /// 
 void onFileDownloadStart(DownloadStartRequest request) async {
    String downloadurl = request.url.toString();
    OLogger.d("开始下载文件，${request.suggestedFilename} , ${request.contentDisposition} , ${request.contentLength} , ${request.mimeType}  ");
    OLogger.d("开始下载文件，url : $downloadurl");
    String? fileName = request.suggestedFilename;
    if (fileName == null || fileName.isEmpty) {
      var contentDisposition = request.contentDisposition;
      if (contentDisposition!=null && contentDisposition.isNotEmpty) {
          var i = contentDisposition.indexOf("''");
          if (i < 0) {
            i = 0;
          }
          fileName = contentDisposition.substring(i);
      }
    }
    OLogger.d("下载文件名： $fileName");
    if (fileName == null || fileName.isEmpty) {
      OLogger.e("文件名称为空，无法下载");
      return;
    }
    String md5 = Md5Util.encode(downloadurl);
    String? filePath = await O2FilePathUtil.getProcessFileDownloadLocalPath(md5, fileName);
    if (filePath == null || filePath.isEmpty) {
      OLogger.e("文件本地存储路径为空，无法下载");
      return;
    }
    try {
       var file = File(filePath);
      if (!file.existsSync()) {
        Loading.show();
        await O2HttpClient.instance.downloadFile(downloadurl, filePath);
        Loading.dismiss();
      }
      _openAttachmentFile(filePath, fileName);
    } on Exception catch (e) {
      Loading.showError(e.toString());
    }
  }

  ///
  /// 打开附件
  ///
 void _openAttachmentFile(String filePath, String fileName) {
    if (filePath.isImageFileName) {
      PreviewImagePage.open(filePath, fileName);
    } else if (filePath.isVideoFileName) {
      VideoPlayerPage.openLocalVideo(filePath, title: fileName);
    }  else {
      channel.openLocalFile(filePath);
    }
  }


}